package com.yicheng.controller;


import com.yicheng.entity.User;
import com.yicheng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public Map<String, Object> findAll(Integer page, String rows){
//        System.out.println("前后端连接成功");
        Map<String, Object> map = new HashMap<>();
        List<User> results = userService.list();
        map.put("total", 10);
        map.put("totalPage", 1);
        map.put("page", page);
        map.put("rows", rows);
        map.put("results", results);
        return map;
    }

    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody User user){
        HashMap<String, Object> map = new HashMap<>();
//        System.out.println("添加成功");
        try{
            userService.save(user);
            map.put("success",true);
            map.put("msg","添加用户信息成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg", "添加用户失败，日期可能不存在");
        }
        return map;
    }

    @GetMapping("/delete")
    public Map<String, Object> delete(Integer id){
        HashMap<String, Object> map = new HashMap<>();
        try{
            userService.removeById(id);
            map.put("success",true);
            map.put("msg","删除用户信息成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg", "删除用户失败"+e.getMessage());
        }
        return map;
    }

    @GetMapping("/findOne")
    public User findOne(Integer id){//以后记得所有返回的东西都统一格式，这里就算了，因为重点不是在弄这个
        return userService.getById(id);
    }


    @PostMapping("/update")
    public Map<String, Object> update(@RequestBody User user){
        HashMap<String, Object> map = new HashMap<>();
        try {
            userService.updateById(user);
            map.put("success", true);
            map.put("msg", "用户信息更新成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success", false);
            map.put("msg", "用户信息更新失败");
        }
        return map;
    }
}
